#include "analy/logic/ToolLogicRF.h"


ToolLogicRF::ToolLogicRF(QMap<QString, QMap<QString, QString>> &_RGLRLSMAP_,
                         QSqlDatabase *DB,
                         QMap<QString, QString> &_QSSMAP_)
    : ToolWin(_RGLRLSMAP_, DB, _QSSMAP_){
}

void ToolLogicRF::abstract_systemexit(){
    QList<QString> items({"Exit", "Ignore"});
    MessageBoxQ *HintMessage = new MessageBoxQ(this,
                                               items,
                                               MessageBoxQ::MSG_Error,
                                               "Question",
                                               "Are You To Be Exit?");
    connect(HintMessage, &MessageBoxQ::checkEvent, this, &ToolLogicRF::abstract_systemexit_dispose);
    diary("system exit question", Diary::Debug)
}

void ToolLogicRF::abstract_systemexit_dispose(QPushButton *button){
    if (button->text() == "Exit"){
        emit sg_system_quit(true, NT::WIN_QUIT_ATTRIBUTE::CHILD_TOOL_QUIT);
        if (SP_sralPort->isOpen()) SP_sralPort->close();
        if (SPitem_viewWidget->isVisible()) SPitem_viewWidget->setVisible(false);
        if (SRLP_LOOPGETP_QTIER.isActive()) SRLP_LOOPGETP_QTIER.stop();
        if (GLOBAL_DBLOOP_QTIER.isActive()) GLOBAL_DBLOOP_QTIER.stop();
        if (TOOL_MENUADJST_QTIER .isActive()) TOOL_MENUADJST_QTIER.stop();
        if (SRLP_DLRMV_QTIER .isActive()) SRLP_DLRMV_QTIER.stop();
        if (SRLP_LOOPGETP_QTIER .isActive()) SRLP_LOOPGETP_QTIER.stop();
        if (SRLP_HLDLECHO_QTIER .isActive()) SRLP_HLDLECHO_QTIER.stop();
        if (GLOBAL_ARGUR_QTIER .isActive()) GLOBAL_ARGUR_QTIER.stop();
        if (SRLP_HLDLTRIGG_QTIER .isActive()) SRLP_HLDLTRIGG_QTIER.stop();
        if (SRLP_CMDLOOP_QTIER .isActive()) SRLP_CMDLOOP_QTIER.stop();
        close();
        diary("exec system exit", Diary::Debug)
    }
}

void ToolLogicRF::abstract_function_cchoice(){
    if (impact_swtc[RPLKEY.UPD_VIEW_STATE])
    {
        if (impact_int[RPLKEY.CUT_VIEW_INDEX] == 1) {
            impact_swtc[RPLKEY.UPD_VIEW_STATE] = false;
            impact_int[RPLKEY.CUT_VIEW_INDEX] += 1;
        }
        else
        {
            impact_int[RPLKEY.CUT_VIEW_INDEX] -= 1;
        }
    }
    else
    {
        if (impact_int[RPLKEY.CUT_VIEW_INDEX] == RegisterSpToolsCount)
        {
            impact_swtc[RPLKEY.UPD_VIEW_STATE] = true;
            impact_int[RPLKEY.CUT_VIEW_INDEX] -= 1;
        }
        else
        {
            impact_int[RPLKEY.CUT_VIEW_INDEX] += 1;
        }
    }
    diary(QString("current function idnex: %1 count: %2").arg(
                           QString::number(impact_int[RPLKEY.CUT_VIEW_INDEX]),
                           QString::number(RegisterSpToolsCount)),
                           Diary::Debug)
    abstract_function_dispose();
}

void ToolLogicRF::abstract_function_mchoice(QAction *Action){
    QString MenuText = Action->objectName();
    if (MenuText == TL_AnlyAC->objectName())
    {
        impact_int[RPLKEY.CUT_VIEW_INDEX] = 1;
        impact_swtc[RPLKEY.UPD_VIEW_STATE] = false;
    }
    else if (MenuText == TL_QrcodeAC->objectName())
    {
        impact_int[RPLKEY.CUT_VIEW_INDEX] = 2;
    }
    else if (MenuText == TL_SerialAC->objectName())
    {
        impact_int[RPLKEY.CUT_VIEW_INDEX] = RegisterSpToolsCount;
        impact_swtc[RPLKEY.UPD_VIEW_STATE] = true;
    }
    diary(QString("current action text: %1, idnex: %2").arg(MenuText, impact_int[RPLKEY.CUT_VIEW_INDEX]), Diary::Debug)
    abstract_function_dispose();
}

void ToolLogicRF::abstract_function_dispose(){
    BS_listWidget->clear();
    if (impact_int[RPLKEY.CUT_VIEW_INDEX] == 1)
    {
        BS_listWidget->setSelectionMode(QListWidget::SingleSelection);
        PBL_centraStackWidget->setCurrentWidget(DT_scdtEdit);
        //#=======secondary option
        AS_pasteAC->setVisible(true);
        AS_rscopyAC->setVisible(true);
        AS_cpcolumnAC->setVisible(true);
        AS_numputAC->setVisible(true);
        AS_TableView->menuAction()->setVisible(true);
        //#=======secondary option
        TR_actionBut->setVisible(true);
        FL_fileaddBut->setVisible(true);
        AS_assistBut->setVisible(true);
        DT_scview->setVisible(true);
        DT_rsview->setVisible(true);
        SP_serialBut->setVisible(false);
        DT_remove->setVisible(false);
        DT_hlview->setVisible(false);
        DT_scview->doconfigur_text("数据");
        DT_rsview->doconfigur_text("结果");
        DT_exec->doconfigur_text("执行");
        VW_viewcutBut->setText("<解析工具>");
        GLOBAL_ARGUR_QTIER.start();
        if (SRLP_LOOPGETP_QTIER.isActive()) SRLP_LOOPGETP_QTIER.stop();
        if (SPitem_viewWidget->isVisible()) SPitem_viewWidget->setVisible(false);
        impact_ttype.insert(RPLKEY.CUT_FUNCNAME, NT::CUT_ANALYTOOL);
        impact_ttype.insert(RPLKEY.CUT_EXBUTCHANGE, NT::CUT_ANALYLIST);
    }

    else if (impact_int[RPLKEY.CUT_VIEW_INDEX] == 2)
    {
        PBL_centraStackWidget->setCurrentWidget(QR_Widget);
        //#=======secondary option
        AS_pasteAC->setVisible(false);
        AS_rscopyAC->setVisible(false);
        AS_cpcolumnAC->setVisible(false);
        AS_numputAC->setVisible(false);
        AS_TableView->menuAction()->setVisible(false);
        //#=======secondary option
        DT_remove->setVisible(true);
        FL_fileaddBut->setVisible(false);
        TR_actionBut->setVisible(false);
        SP_serialBut->setVisible(false);
        DT_hlview->setVisible(false);
        DT_rsview->setVisible(false);
        DT_scview->doconfigur_text("二维码");
        DT_exec->doconfigur_text("生成二维码");
        VW_viewcutBut->setText("<二维码工具>");
        impact_ttype.insert(RPLKEY.CUT_FUNCNAME, NT::CUT_QRCODETOOL);
        impact_ttype.insert(RPLKEY.CUT_EXBUTCHANGE, NT::CUT_QRCODELIST);
        GLOBAL_ARGUR_QTIER.start();
        if (SRLP_LOOPGETP_QTIER.isActive()) SRLP_LOOPGETP_QTIER.stop();
        if (SPitem_viewWidget->isVisible()) SPitem_viewWidget->setVisible(false);
    }

    else if (impact_int[RPLKEY.CUT_VIEW_INDEX] == 3)
    {
        PBL_centraStackWidget->setCurrentWidget(SP_Widget);
        FL_fileaddBut->setVisible(false);
        TR_actionBut->setVisible(false);
        //#=======secondary option
        AS_rscopyAC->setVisible(false);
        AS_cpcolumnAC->setVisible(false);
        AS_numputAC->setVisible(false);
        AS_TableView->menuAction()->setVisible(false);
        //#=======secondary option
        AS_assistBut->setVisible(true);
        SP_serialBut->setVisible(true);
        DT_remove->setVisible(true);
        DT_hlview->setVisible(true);
        DT_scview->setVisible(true);
        DT_rsview->setVisible(true);
        DT_scview->doconfigur_text("连接");
        DT_rsview->doconfigur_text("命令");
        VW_viewcutBut->setText("<串口工具>");
        DT_exec->doconfigur_text("打开串口");
        impact_ttype.insert(RPLKEY.CUT_FUNCNAME, NT::CUT_SERIALTOOL);
        impact_ttype.insert(RPLKEY.CUT_EXBUTCHANGE, NT::CUT_CONNECTLIST);
        SRLP_LOOPGETP_QTIER.start();
        GLOBAL_ARGUR_QTIER.start(); //#寻找所有数据，展示已应用的数据，不直接加载列表，由 data_serial_summaryconfig 函数加载，因为NikeName初始为空
        SRLP_HLDLECHO_QTIER.start();

    }
    diary(QString("current function index: %1").arg(impact_int[RPLKEY.CUT_VIEW_INDEX]), Diary::Debug)
}

void ToolLogicRF::dialog_rsmatching(int type){
    if (type == 0 ){
        QString File = QFileDialog::getOpenFileName(this,
                                                    "add file",
                                                    impact_str["mdrs-follow-directory"],
                                                    "All files (*)");
        if (!File.isEmpty()){
            MessageBoxQ *FileDiaBox = new MessageBoxQ(this,
                                                      {"Add The Path", "Ignore"},
                                                      MessageBoxQ::MSG_Question,
                                                      "add file",
                                                      QString("File Verify: {%1}").arg(File));
            impact_str["dia-temporary-file"] = File;
            connect(FileDiaBox, &MessageBoxQ::checkEvent, this, &ToolLogicRF::dialog_dispose_file);
        }
    } else {
        QString Folder = QFileDialog::getExistingDirectory(this,
                                                           "add folder",
                                                           impact_str["mdrs-follow-directory"],
                                                           QFileDialog::ShowDirsOnly);
        if (!Folder.isEmpty()){
            MessageBoxQ *FileBox = new MessageBoxQ(this,
                                    {"Add The Path", "Ignore"},
                                    MessageBoxQ::MSG_Question,
                                    "Add Folder",
                                    QString("File Verify: {%1}").arg(Folder));
            impact_str["dia-temporary-folder"] = Folder;
            QObject::connect(FileBox, &MessageBoxQ::checkEvent, this, &ToolLogicRF::dialog_dispose_folder);
        }
    }
}

void ToolLogicRF::dialog_dispose_folder(QPushButton *But){
    if (But->objectName() != "Ignore"){
        if (impact_str["mdrs-follow-directory"] == "follow")
        {
            impact_str["mdrs-follow-directory"] = impact_str["dia-temporary-folder"];
        }
    }
}

void ToolLogicRF::dialog_dispose_file(QPushButton *But){
    if (But->objectName() != "Ignore"){
        if (impact_str["mdrs-follow-directory"] == "follow")
        {
            impact_str["mdrs-follow-directory"] = QFileInfo(impact_str["dia-temporary-file"]).filePath();
        }
    }
}

void ToolLogicRF::roofmenu_option(QAction *action){
    if (action->objectName() == FL_sgfileAC->objectName())
    {
        dialog_rsmatching(0);

    }

    else if (action->objectName() == FL_folderAC->objectName())
    {
        dialog_rsmatching(1);

    }

    else if (action->objectName() == TR_PauseAC->objectName())
    {
        impact_int[RPLKEY.UPD_THREAD_STATE] = NT::THREAD_PAUSE;

    }

    else if (action->objectName() == TR_WipeAC->objectName())
    {
        impact_int[RPLKEY.UPD_THREAD_STATE] = NT::THREAD_TERMINATED;

    }

    else if (action->objectName() == TR_RecoverAC->objectName())
    {
        impact_int[RPLKEY.UPD_THREAD_STATE] = NT::THREAD_RECOVER;

    }

    else if (action->objectName() == AS_pasteAC->objectName())
    {
        // BoilPool->run(ThreadPoint::ANALY_STICK);

    }

    else if (action->objectName() == AS_rscopyAC->objectName())
    {
        if (impact_ttype[RPLKEY.CUT_FUNCNAME] == NT::CUT_SERIALTOOL)
        {
            SP_serialInfoEdit->copy();
        }
        else if (impact_ttype[RPLKEY.CUT_FUNCNAME] == NT::CUT_ANALYTOOL)
        {
            DT_scdtEdit->copy();
        }
    }

    else if (action->objectName() == As_cpviewAC->objectName())
    {
//        if self.WTstateDict["tableview"]:
//            self.TableViewWidget.setVisible(True)

    }

     else if (action->objectName() == As_xmviewAC->objectName())
    {

    }

    else if (action->objectName() == AS_cpcolumnAC->objectName())
    {
        emit VariantPopuEvent(qMakePair(NT::ANALYFUNC_BACK_COMPARE, QVariant(0)));
    }

    else if (action->objectName() == AS_numputAC->objectName())
    {
//        self.centra_numbers_messagebox()
    }

    else if (action->objectName() == AS_multiAC->objectName())
    {
        BS_listWidget->setSelectionMode(QAbstractItemView::MultiSelection);

    }

    else if (action->objectName() == AS_singleAC->objectName())
    {
        BS_listWidget->setSelectionMode(QAbstractItemView::SingleSelection);

    }

    else if (action->objectName() == AS_continueAC->objectName())
    {
        BS_listWidget->setSelectionMode(QAbstractItemView::ContiguousSelection);
    }

    else if (action->objectName() == SP_taBarSwcAC->objectName())
    {
        if (SP_TabWidget->isVisible())
        {
            SP_taBarSwcAC->setText("工具栏可见");
            SP_TabWidget->setVisible(false);
        }
        else
        {
            SP_taBarSwcAC->setText("工具栏隐藏");
            SP_TabWidget->setVisible(true);
        }
    }
}

bool ToolLogicRF::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
{
    /*
     * WM_SHOWWINDOW  24
     * WM_GETMINMAXINFO 36

    */
    MSG *winsuerMsg = (MSG *)message;
    if (winsuerMsg->message == WM_CLOSE)
    {
        abstract_systemexit();
        return true;
    }
    return QWidget::nativeEvent(eventType, message, result);
}

void ToolLogicRF::abstract_dtbs_timer(){
    if (!DATABASE->isOpen()){
        DATABASE->open();
        if (DATABASE->isOpen()){
            diary("database reconnect successful", Diary::Success)
        } else {
            QSqlDatabase *_DATABASE = new QSqlDatabase();
            *_DATABASE = _DATABASE->addDatabase("QSQLITE");
            _DATABASE->setDatabaseName((*__RLMAP__)["PATH"]["DBPATH"]);
            _DATABASE->open();
            DATABASE = _DATABASE;
        }
    diary(QString("database stat: %1").arg(DATABASE->isOpen()), Diary::Debug);
    }
}
